<template>
  <div class="upload_image-container" :class="{hasCacheImg: cacheImg}">
    <div class="upload_image">
      <input @change="selectedImg" :disabled="disabled" class="upload_input" title=" " ref="upload" accept="image/*" type="file" capture="camera">

      <div @click="showImg" :class="{'has_take': cacheImg,'handle_uploadImg_show':isIDImg}" :style="backgroundImg(cacheImg)" class="show_upload_img" >
        <!--      <span v-if="!disabled" v-show="cacheImg" @click.stop="retake" class="retake"></span>-->

        <span v-if="!disabled" v-show="isIDImg && !cacheImg" @click.stop="retake" class="retake"></span>
        <!-- <span v-if="!disabled" v-show="cacheImg" @click.stop="retake" class="retake2"></span> -->
      </div>

      <div v-show="showBigImg" @click="showBigImg = false" class="show_big_img">
        <img :src="cacheImg" alt="show img">
        <div v-if="!disabled" @click.stop.prevent="retake" class="retake_btn"></div>
        <div class="close_big_img"></div>
      </div>

      <div class="label">{{ title }}</div>
    </div>
  </div>
</template>

<script>
  import Popup from '@/components/popup';
  // import Hybrid from '@/components/uzone-hybrid';
  import compression from './compression-image';

  export default {
    name: 'uploadImage',
    props: {
      pageTrackerInfo: {
        type: Object,
        default: () => {}
      },
      isIDImg: {
        default: false
      },
      value: {
        default: ''
      },
      disabled: {
        default: false
      },
      title: {
        default: ''
      }
    },
    data() {
      return {
        cacheImg: '', // 缓存上传的图片
        showBigImg: false, // 是否展示大图
      };
    },
    watch: {
      value(val) {
        // console.log(val);
        if (val && typeof val === 'string') {
          this.cacheImg = val;
        }
      }
    },
    methods: {
      selectedImg() {
        // 认证信息页 - 上传身份证 - 点击
        this.$buryPoint.action({
          eventName: 'authInfo_idCard_upload_click',
          ...this.pageTrackerInfo
        });
        const uploader = this.$refs.upload;
        if (uploader.files.length > 0) {
          const file = uploader.files[0];
          const { size, type } = file;
          const maxSize = 100 * 1024; // 最大100
          // const limitSize = 1024 * 1024 * 10;
          // const isLt10M = size / 1024 / 1024 <= 10;
          if (type.indexOf('image/') !== 0) {
            Popup('Only upload pictures', 'warn');
            return;
          }
          // if (!isLt10M) {
          //   this.$toast('Upload image size cannot exceed 10MB!'); // 上传图片大小不能超过 10MB!
          //   return;
          // }
          // if (size > limitSize) {
          //   Popup('Pictures max 10M', 'warn');
          //   return;
          // }
          if (size > maxSize) {
            // 如果图片大于350K，则进行压缩
            compression(file, this.uploadImg, maxSize);
          } else {
            // 如果小于350K，则直接上传
            // this.readFile(file);
            this.uploadImg(file);
          }
        }
      },
      // 读取文件进行展示
      readFile(file) {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.cacheImg = reader.result;
          this.$emit('input', file);
        };
      },
      uploadImg(file) {
        this.$refs.upload.value = ''; // 清除input图片缓存
        const { size } = file;
        if (size === 0) {
          this.$toast('Picture error, please re-upload!');
          return;
        }
        const params = {
          file,
          key: '10483112dee06aadd2616848b7d020bb',
        };
        const formatData = new FormData();
        Object.keys(params).forEach(key => {
          formatData.append(key, params[key]);
        });
        this.$api.fileUpload(formatData).then(res => {
          const { status, error, data } = res;
          if ('1' === status && ('00000000' === error || '0000' === error) && data) {
            // const oldUrl = 'http://fastdfs.pesopop.com:9011';
            // const newUrl = 'https://fastdfs.pesopop.com:19011';
            if (data.url && data.length > 0) {
              data.url = data.url.replace(oldUrl, newUrl);
            }
            if (!data.url) {
              this.$toast('Image upload failed, please upload again!');
              return;
            }
            this.cacheImg = data.url;
            this.$emit('input', data.url);
            this.$emit('upload',data);
          }
        });
      },
      backgroundImg(url) {
        // console.log(url);
        const style = {};
        if (url && typeof url === 'string') {
          style.backgroundImage = `url(${url})`;
        }
        return style;
      },
      // 查看上传的图片
      showImg() {
        if (this.cacheImg) {
          this.showBigImg = true;
        } else {
          this.handleFileInputClick();
        }
      },
      // 重新上传照片
      retake() {
        this.showBigImg = false;
        // this.triggerClick(this.$refs.upload);
        this.handleFileInputClick();
      },
      // 触发点击事件
      triggerClick(node) {
        if (document.createEvent) {
          const evt = document.createEvent('MouseEvents');
          evt.initEvent('click', true, false);
          node.dispatchEvent(evt);
        } else if (document.createEventObject) {
          node.fireEvent('onclick');
        } else if (typeof node.onclick === 'function') {
          node.onclick();
        }
      },
      // 点击上传文件
      handleFileInputClick() {
        this.triggerClick(this.$refs.upload);
//        const hybrid = new Hybrid(this.$os.android ? 'android' : 'ios');
//        const me = this;
//        hybrid.action('takePhoto', {
//          callback: function(data) {
//            if (+data.status === 1) {
//              me.triggerClick(me.$refs.upload);
//            }
//          }
//        });
      }
    },
    created() {
      if (this.value && typeof this.value === 'string') {
        this.cacheImg = this.value;
      }
    },
  };
</script>

<style lang="scss" scoped>
  .upload_image-container {
    // background: #A4B1FC;
    // border-radius: 16px;
    // padding: 70px 112px;
    height: 388px;
    overflow: hidden;
    padding: 48px 90px;
    background-color: #fff;
    &.hasCacheImg {
      padding: 0;
    }
  }
  .upload_image{
    display: inline-block;
    position: relative;
    // overflow: hidden;
    width: 100%;
    height: 100%;
  }
  .upload_input{
    /*display: none;*/
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    opacity: 0;
    cursor: pointer;
    width: 100%;
  }
  .show_upload_img{
    background-size: contain;
    width: 198px;
    flex-shrink: 1;
    height: 142px;
    // border-radius: 8px;
    position: relative;
    z-index: 11;
    margin: 0 auto;
  }
  .handle_uploadImg_show{
    background: url("~@/assets/imgs/img_handle_bg.png") no-repeat center center;
    background-size: cover;
    width: 100%;
    height: 100%;
    // border-radius: 8px;
    position: relative;
    z-index: 11;
    margin: 0 auto;
  }
  .retake{
    background: url("~@/assets/imgs/img_handle_add.png") no-repeat center center;
    background-size: cover;
    width: 104px;
    height: 104px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .retake2{
    background: url("~@/assets/imgs/icon/icon_camera_2.png") no-repeat center center;
    background-size: cover;
    width: 60px;
    height: 60px;
    position: absolute;
    right: 36px;
    bottom: 28px;
  }
  .has_take{
    /*z-index: 11;*/
    background-size: cover;
  }
  .show_big_img{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 100;
    text-align: center;
    img{
      max-height: 100%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .retake_btn{
    background: url("~@/assets/imgs/icon/icon_camera.png") no-repeat center center;
    background-size: cover;
    width: 150px;
    height: 150px;
    position: absolute;
    bottom: 72px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 10;
  }
  .close_big_img{
    background: url("~@/assets/imgs/icon_close_white.png") no-repeat center center;
    background-size: cover;
    width: 48px;
    height: 48px;
    position: absolute;
    bottom: 123px;
    right: 87px;
    z-index: 10;
  }
  .label {
    display: none;
    margin-top: 16px;
    color: #FFFFFF;
    font-size:286px;
    font-weight: normal;
    text-align: center;
    line-height: 1;
  }
</style>
